<template>
  <div class="register-page">
    <div class="register-container">
      <!-- 左侧背景 -->
      <div class="register-background">
        <div class="background-content">
          <h2 class="background-title">智问社区</h2>
          <p class="background-text">加入我们，分享您的专业知识</p>
        </div>
      </div>
      
      <!-- 右侧注册表单 -->
      <div class="register-form-container">
        <div class="register-header">
          <div class="logo-container" @click="$router.push('/')">
            <div class="logo-bg">
              <el-icon><QuestionFilled /></el-icon>
            </div>
            <h1 class="site-name">智问社区</h1>
          </div>
          <h2 class="register-title">创建新账号</h2>
          <p class="register-subtitle">加入专业问答社区，获取和分享知识</p>
        </div>
        
        <!-- 注册表单 -->
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="register-form"
          @submit.prevent="handleRegister"
        >
          <!-- 用户名 -->
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="用户名"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 邮箱 -->
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 验证码 -->
          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input v-model="registerForm.captcha" placeholder="验证码">
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" :disabled="captchaLoading" @click="getCaptcha">
                {{ captchaLoading ? '获取中...' : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
          
          <!-- 密码 -->
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 确认密码 -->
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 同意条款 -->
          <el-form-item prop="agreement">
            <el-checkbox v-model="registerForm.agreement">
              我已阅读并同意
              <router-link to="/terms" class="terms-link">服务条款</router-link>
              和
              <router-link to="/privacy" class="terms-link">隐私政策</router-link>
            </el-checkbox>
          </el-form-item>
          
          <!-- 注册按钮 -->
          <el-button
            type="primary"
            class="register-button"
            :loading="loading"
            @click="handleRegister"
          >注册</el-button>
          
          <!-- 第三方注册 -->
          <div class="third-party-register">
            <div class="divider">
              <span>或使用以下方式注册</span>
            </div>
            <div class="third-party-buttons">
              <el-button class="social-button">
                <el-icon><Promotion /></el-icon>
              </el-button>
              <el-button class="social-button">
                <el-icon><User /></el-icon>
              </el-button>
              <el-button class="social-button">
                <el-icon><Platform /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 登录链接 -->
          <div class="login-link-container">
            已有账号? <router-link to="/login" class="login-link">立即登录</router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { register, getCaptcha as getCaptchaApi } from '../api/auth';
import { 
  User, 
  Lock, 
  Message,
  Key, 
  QuestionFilled, 
  Promotion,
  Platform
} from '@element-plus/icons-vue';

const router = useRouter();
const loading = ref(false);
const captchaLoading = ref(false);
const registerFormRef = ref(null);
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  captchaKey: '',
  agreement: false
});

// 自定义校验规则：确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 注册表单校验规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  agreement: [
    {
      validator: (_, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意服务条款和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 获取验证码
const getCaptcha = async () => {
  if (!registerForm.value.email) {
    ElMessage.warning('请先输入邮箱');
    return;
  }
  
  try {
    captchaLoading.value = true;
    
    // 调用验证码获取API
    const res = await getCaptchaApi(registerForm.value.email);
    
    registerForm.value.captchaKey = res.data.captchaKey;
    // 开发环境直接获取验证码，生产环境需要用户从邮箱获取
    registerForm.value.captcha = res.data.captcha;
    
    ElMessage.success('验证码已发送到您的邮箱');
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error(error.message || '获取验证码失败');
  } finally {
    captchaLoading.value = false;
  }
};

const handleRegister = async () => {
  if (registerFormRef.value) {
    try {
      await registerFormRef.value.validate();
      loading.value = true;
      
      // 准备注册数据
      const registerData = {
        username: registerForm.value.username,
        email: registerForm.value.email,
        password: registerForm.value.password,
        confirmPassword: registerForm.value.confirmPassword,
        captcha: registerForm.value.captcha,
        captchaKey: registerForm.value.captchaKey
      };
      
      // 调用注册接口
      await register(registerData);
      
      ElMessage.success('注册成功，请登录');
      
      // 注册成功，跳转到登录页
      router.push('/login');
    } catch (error) {
      console.error('注册失败:', error);
      ElMessage.error(error.message || '注册失败，请重试');
    } finally {
      loading.value = false;
    }
  }
};
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.register-container {
  display: flex;
  width: 900px;
  height: 660px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  overflow: hidden;
}

.register-form-container {
  flex: 1;
  background-color: #fff;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

.register-header {
  margin-bottom: 30px;
}

.logo-container {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  cursor: pointer;
}

.logo-bg {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.site-name {
  margin: 0 0 0 10px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.register-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px;
}

.register-subtitle {
  color: #666;
  margin: 0;
}

.register-form {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-container .el-input {
  flex: 1;
}

.terms-link {
  color: #409eff;
  text-decoration: none;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  margin-bottom: 24px;
}

.third-party-register {
  margin-bottom: 24px;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  color: #999;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #eee;
  margin: 0 16px;
}

.third-party-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.social-button {
  width: 40px;
  height: 40px;
  padding: 0;
  border-radius: 50%;
  border: 1px solid #eee;
}

.login-link-container {
  text-align: center;
  color: #666;
  font-size: 14px;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.register-background {
  width: 40%;
  background: linear-gradient(135deg, #1e3a8a 0%, #2563eb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  padding: 40px;
}

.background-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 16px;
}

.background-text {
  font-size: 18px;
  opacity: 0.9;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .register-container {
    width: 100%;
    height: 100vh;
    border-radius: 0;
  }
  
  .register-background {
    display: none;
  }
}
</style> 